import store from "@/store";
import { createRouter, createWebHashHistory } from "vue-router";

const Layout = () => import("@/views/Layout");
const Home = () => import("@/views/home/index");
const Category = () => import("@/views/category/index");
const Search = () => import("@/views/search/index");
const Goods = () => import("@/views/goods/index");
const Login = () => import("@/views/login/index");
const Cart = () => import("@/views/cart/index");
const Checkout = () => import("@/views/checkout/index");
const Pay = () => import("@/views/pay/index");
const PayResult = () => import("@/views/pay/result");

// 1. 定义路由规则：什么路径显示什么组件
const routes = [
  {
    path: "/",
    component: Layout,
    children: [
      { path: "/", component: Home },
      { path: "/category/:id", component: Category },
      { path: "/search", component: Search },
      { path: "/product/:id", component: Goods },
      { path: "/cart", component: Cart },
      { path: "/user/checkout", component: Checkout },
      { path: "/user/pay", component: Pay },
      { path: "/user/pay/result", component: PayResult },
    ],
  },
  { path: "/login", component: Login },
];

// 2. createRouter函数是router实例的
const router = createRouter({
  // 3. history 配置路由模式：hash(localhost:8080/#/home)    history(localhost:8080/home)
  // createWebHashHistory() 创建hash模式的路由
  history: createWebHashHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    // 前进后退的时候，回到页面原理滚动的位置（还原浏览器原生效果）
    if (savedPosition) {
      return savedPosition;
    } else {
      // 没有浏览过的到页面顶部
      return { top: 0 };
    }
  },
});

// 访问权限控制
router.beforeEach((to, from, next) => {
  const { profile } = store.state.user;
  // 拦截登录（想去的地址是以/user开头&&未登录）
  if (to.path.startsWith("/user") && !profile.token) {
    // 把你想去的地址传递给登录页面，登录完成根据这个地址进行跳转
    // to.fullPath （包含地址栏的参数） /user/order?page=2
    return next({ path: "login", query: { redirectUrl: to.fullPath } });
  }
  next();
});

export default router;
